import React, { useContext, useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Modal,
  TreeSelect,
  Checkbox,
  InputNumber,
  Space,
  Tabs,
  Row,
  Col,
  Upload,
  Select,
  Transfer,
  Table,
  Popconfirm,
} from 'antd';
import { ExclamationCircleOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import 'braft-editor/dist/index.css';
import ImgQuick from '@/pages/admin/imgQuick';
import UploadUtil from '@/components/UploadUtil';
import BraftEditor, { ControlType } from 'braft-editor';
import ChoiceCourse from './ChoiceCourse';

import { FormInstance } from 'antd/lib/form';
const { confirm } = Modal;
const { TabPane } = Tabs;
const currControl = 'Edu_CourseCopy';

const EditableContext = React.createContext<FormInstance<any> | null>(null);
//形参类型
interface Item {
  keys: string;
  edu_Course: string;
  orderId: number;
  id: string;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  keys: React.ReactNode;
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
  handleDelete: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  keys,
  children,
  dataIndex,
  record,
  handleSave,
  handleDelete,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<Input>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    console.log(record);
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      console.log(values);
      console.log(record);
      // if (values.edu_Course) {
      //   record.edu_Course = values.edu_Course;
      // }
      if (values.orderId) {
        record.orderId = values.orderId;
      }
      toggleEdit();
      handleSave(record);
      console.log(record);
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `请输入${title} .`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];
interface DataType {
  keys: React.Key;
  edu_Course: string;
  courseId: string;
  courseExpandId: string;
  orderId: number;
  id: string;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
class CourseEdit extends React.Component<any, any> {
  columnsExpand: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[];

  constructor(props: any) {
    super(props);
    this.columnsExpand = [
      {
        title: '课程名称',
        dataIndex: 'edu_Course',
        width: 230,
        render: (text: any, record: any) => <span>{record.edu_Course.title}</span>,
      },
      {
        title: '排序号',
        width: 120,
        dataIndex: 'orderId',
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'actions',
        render: (text: any, record: any) => (
          <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];
    this.state = {
      loading: false,
      datas: {},
      cascaderOption: [],
      courseTags: [],
      contentEditor: '',
      imageUrl: '',
      imgList: [],
      userArr: [],
      targetKeys: [],
      targetProKeys: [],
      targetExpKeys: [],
      selectedKeys: [],
      selectedProKeys: [],
      selectedExpKeys: [],
      couponDatas: [],
      promotions: [],
      courseData: [],

      fileList: [],
      visible4: false,
      visibleExpand: false,
      contents: '',
      selectValue: '',
      params: {},
      value: [],
      expandList: [],
      loadingExpand: false,
      selectedRowKeys: [],
      totalCountC: 0,
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData } = this.props;
    this.fetchCategory();
    this.fetchUsers();
    this.fetchCoupon();
    this.fetchPromotion();
    this.fetchTags();
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
      this.getExpandList(ParentData.id);
    }
  }

  getData = (id: number) => {
    const { dispatch } = this.props;
    this.setState({ loading: true });
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;
        console.log(result);
        if (result.contents) {
          this.setState({ contentEditor: result.contents });
          result.contents = BraftEditor.createEditorState(result.contents);
        }

        result.coupons = result.coupons?.split(',');
        result.promotionId = result.promotionId?.split(',');
        result.expand = result.expand?.split(',');
        if (result.apprvStaus) {
          if (result.apprvStaus == 'A') {
            result.apprvStaus = '已审核';
          } else if (result.apprvStaus == 'U') {
            result.apprvStaus = '未审核';
          } else if (result.apprvStaus == 'R') {
            result.apprvStaus = '审核不通过';
          }
        }
        this.setState({
          datas: result,
          targetKeys: result.coupons,
          targetProKeys: result.promotionId,
          targetExpKeys: result.expand,
          loading: false,
        });
        if (result.imageUrl) {
          var obj = {
            uid: result.imageUrl,
            name: result.imageUrl,
            response: {
              result: result.imageUrl,
            },
            status: 'done',
            url: UploadUtil.imgServ + result.imageUrl,
          };
          const { fileList } = this.state;
          fileList.push(obj);

          this.setState({ fileList });
        }
        this.setState({ defaultData: result });

        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  //拓展知识list
  getExpandList = (id: any) => {
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          courseId: id,
        },
        control: 'Edu_CourseExpand',
      })
      .then(() => {
        const resp = this.props.response.result;
        if (resp) {
          this.setState({ expandList: resp.items, loadingExpand: false });
        }
      });
  };
  fetchCoupon = () => {
    this.props
      .dispatch({
        type: 'Abp/getAll',
        payload: { SkipCount: 0, MaxResultCount: 9999 },
        control: 'Coupon',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var couponDatas: any = [];
          resp.result.items.forEach((element: any) => {
            couponDatas.push({
              key: element.id,
              title: element.title,
              description: element.memo,
            });
          });
          this.setState({ couponDatas });
        }
      });
  };
  fetchPromotion = () => {
    this.props
      .dispatch({
        type: 'Abp/getAll',
        payload: { SkipCount: 0, MaxResultCount: 9999 },
        control: 'Edu_Promotion',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var promotions: any = [];
          resp.result.items.forEach((element: any) => {
            promotions.push({
              key: element.id,
              title: element.title,
              description: element.memo,
            });
          });
          this.setState({ promotions });
        }
      });
  };

  fetchUsers = () => {
    this.props
      .dispatch({
        type: 'Abp/getAll',
        payload: { SkipCount: 0, MaxResultCount: 9999 },
        control: 'User',
      })
      .then(() => {
        var resp = this.props.response.result?.items;
        if (resp) {
          var arrs: any = [];
          resp.forEach((element: any) => {
            var obj = {
              value: element.id,
              text: element.fullName,
            };
            arrs.push(obj);
          });
          this.setState({ userArr: arrs });
        }
      });
  };
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'course' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  fetchTags = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'courseTags' },
      })
      .then(() => {
        const resp = this.props.Category.response.result;
        if (resp) {
          resp.forEach((item: any) => {
            const temp = item.value;
            item.value = item.title;
            item.title = item.title + temp;
            if (item.children !== null) {
              item.children.forEach((ele: any) => {
                ele.value = ele.title;
              });
            }
          });
        }

        this.setState({ courseTags: resp });
      });
  };

  CopyData = () => {
    let model = this.state.datas;
    console.log(model);
    model.id = model.id ? model.id : '';
    this.props
      .dispatch({
        type: 'Abp/copyCourse',
        payload: {
          courseId: model.id,
        },
      })
      .then(() => {
        var resp = this.props.response;
        console.log(resp, 'resp测试');
        if (resp.success) {
          message.success('复制成功！');
          this.formRef.current.setFieldsValue({ model });
          this.props.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  onFinish = async (values: any) => {
    console.log(values);

    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    values.model.contents = this.state.contentEditor;
    if (this.state.fileList) {
      var pics: string[] = [];
      this.state.fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.model.imageUrl = pics.toString();
    }
    if (values.model.apprvStaus) {
      if (values.model.apprvStaus == '已审核') {
        values.model.apprvStaus = 'A';
      } else if (values.model.apprvStaus == '未审核') {
        values.model.apprvStaus = 'U';
      } else {
        values.model.apprvStaus = 'R';
      }
    } else {
      values.model.apprvStaus = 'U';
    }
    values.model.coupons = values.model.coupons?.join(',');
    values.model.promotionId = values.model.promotionId?.join(',');
    values.model.expand = values.model.expand?.join(',');
    if (values.model.tags) {
      values.model.tags = values.model.tags.toString();
    }
    console.log(values.model);

    const { params } = this.props;
    const { stateKey, keywords, cateid, sortBy, ageRge } = params;
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          if (stateKey === -1) {
            //全部
            this.props.fetchDatas(0, null, null, null, keywords, cateid, sortBy, ageRge);
          } else if (stateKey === 1) {
            //免费
            this.props.fetchDatas(0, null, true, null, keywords, cateid, sortBy, ageRge);
          } else if (stateKey === 2) {
            //推荐
            this.props.fetchDatas(0, null, null, true, keywords, cateid, sortBy, ageRge);
          } else if (stateKey === 3) {
            //已审核
            this.props.fetchDatas(0, 'A', null, null, keywords, cateid, sortBy, ageRge);
          } else if (stateKey === 4) {
            //未审核
            this.props.fetchDatas(0, 'U', null, null, keywords, cateid, sortBy, ageRge);
          } else if (stateKey === 5) {
            this.props.fetchDatas(0, 'R', null, null, keywords, cateid, sortBy, ageRge);
          }
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  handleTransChange = (nextTargetKeys: any, direction: any, moveKeys: any) => {
    this.setState({ targetKeys: nextTargetKeys });
  };

  handleSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) => {
    this.setState({
      selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys],
    });
  };
  handleProTransChange = (nextProTargetKeys: any, direction: any, moveKeys: any) => {
    this.setState({ targetProKeys: nextProTargetKeys });
  };

  handleProSelectChange = (sourceProSelectedKeys: any, targetProSelectedKeys: any) => {
    this.setState({
      selectedProKeys: [...sourceProSelectedKeys, ...targetProSelectedKeys],
    });
  };
  //上传图片
  handleUpload = (info: any) => {
    console.log(info);

    if (info.file.status === 'done' && info.fileList.length > 0) {
      this.setState({
        fileList: [info.file],
      });
    } else {
      this.setState({
        fileList: info.fileList,
      });
    }
  };
  /**
   * @param val 控制图片选择框
   */
  clickFun = (val: any) => {
    var obj = {
      uid: val,
      name: val,
      response: {
        result: val,
      },
      status: 'done',
      url: UploadUtil.imgServ + val,
    };
    this.setState({ fileList: [obj], visible4: false });
  };
  handleOnselect = (e: any, node: any) => {
    console.log(e, node);
    e = node.title;
    console.log(e);
    this.setState({ selectValue: node.title });
  };
  myUploadFn = (param: any) => {
    // console.log('param',param);
    const serverURL = UploadUtil.actionURL; //upload 是接口地址
    const xhr = new XMLHttpRequest();
    const fd = new FormData();

    const successFn = (response: any) => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      console.log('response', response);
      //console.log('xhr.responseText', xhr.responseText);
      const upLoadObject = JSON.parse(response.currentTarget.response);

      param.success({
        url: UploadUtil.imgServ + upLoadObject.result,
        meta: {
          id: upLoadObject && upLoadObject.result,
          title: upLoadObject && upLoadObject.result,
          alt: upLoadObject && upLoadObject.result,
          loop: false, // 指定音视频是否循环播放
          autoPlay: false, // 指定音视频是否自动播放
          controls: false, // 指定音视频是否显示控制栏
          poster: '', // 指定视频播放器的封面
        },
      });
    };

    const progressFn = (event: any) => {
      // 上传进度发生变化时调用param.progress
      param.progress((event.loaded / event.total) * 100);
    };

    const errorFn = (response: any) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);

    fd.append('files', param.file);
    xhr.open('POST', serverURL.toString(), true);
    xhr.setRequestHeader('Authorization', UploadUtil.accessToken); //header中token的设置
    xhr.send(fd);
  };
  onSelectChange = (selectedRowKeys: any, values: any) => {
    this.setState({ selectedRowKeys, selectedRowData: values });
  };

  //删除拓展课程
  handleDelete = (id: number) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: 'Edu_CourseExpand',
      })
      .then(() => {
        this.getExpandList(this.props.ParentData.id);
        this.setState({ loadingExpand: true });
      });
  };
  //修改确认编辑框
  handleSave = (row: DataType) => {
    let newData: DataType[] = [];
    const { expandList } = this.state;

    expandList.forEach((element: DataType) => {
      console.log(element);

      if (element.id === row.id) {
        element.edu_Course = row.edu_Course;
        element.courseId = row.courseId;
        element.courseExpandId = row.courseExpandId;
        element.orderId = row.orderId;
        newData.push(element);
      }
      console.log(newData);
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'Abp/update',
      payload: { ...newData[0] },
      control: 'Edu_CourseExpand',
    }).then(() => {
      this.getExpandList(this.props.ParentData.id);
    });
  };
  handleSelect = (val: any, valData: any) => {
    console.log(valData);
  };
  render() {
    const {
      datas,
      loading,
      userArr,
      targetKeys,
      selectedKeys,
      targetProKeys,
      selectedProKeys,
      couponDatas,
      promotions,
      fileList,
      expandList,
      visibleExpand,
    } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const courseId = this.props.ParentData ? this.props.ParentData.id : '';
    const options = userArr.map((d: any) => (
      <Select.Option key={d.value} value={d.value}>
        {d.text}
      </Select.Option>
    ));
    const editorTools: ControlType[] = [
      'undo',
      'redo',
      'text-color',
      'bold',
      'italic',
      'underline',
      'text-align',
      'separator',
      'link',
      'media',
      'clear',
      'font-size',
      'line-height',
      'letter-spacing',
      'font-family',
      'remove-styles',
      'fullscreen',
      'strike-through',
      'text-indent',
      'headings',
    ];
    const text = this.state.datas.id ? <span>保存</span> : <span>添加</span>;

    const columns = this.columnsExpand.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record: DataType) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
          handleDelete: this.handleDelete,
        }),
      };
    });
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本" key="1">
              <div style={{ display: 'none' }}>
                <Form.Item label="id" name={['model', 'id']}>
                  <Input />
                </Form.Item>
                <Form.Item label="imageUrl" name={['model', 'imageUrl']}>
                  <Input />
                </Form.Item>
              </div>
              <Row gutter={4}>
                <Col span={8}>
                  <Form.Item
                    name={['model', 'categoryId']}
                    label="课程分类"
                    rules={[{ required: true, message: '请选择课程分类' }]}
                  >
                    <TreeSelect
                      allowClear
                      value={this.state.value}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={this.state.cascaderOption}
                      placeholder="请选择课程类别"
                      treeDefaultExpandAll
                    />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item name={['model', 'tags']} label="课程标签">
                    <TreeSelect
                      allowClear
                      value={this.state.courseTags}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={this.state.courseTags}
                      placeholder="请选择课程标签"
                      treeDefaultExpandAll
                      multiple
                      onSelect={this.handleOnselect}
                    />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name={['model', 'cType']} label="课程类型">
                    <Select>
                      <Select.Option value="video">视频</Select.Option>
                      <Select.Option value="common">普通</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={2}>
                <Col span={12}>
                  <Form.Item name={['model', 'courseTarget']} label="课程目标">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name={['model', 'title']}
                    rules={[{ required: true, message: '请选择课程标题' }]}
                    label="课程标题"
                  >
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={4}>
                <Col span={12}>
                  <Form.Item name={['model', 'summary']} label="系列课程简介">
                    <Input.TextArea allowClear={true} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name={['model', 'teacherJob']} label="讲师内容">
                    <Input.TextArea allowClear={true} autoSize={{ minRows: 2, maxRows: 6 }} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={4}>
                <Col span={12}>
                  <Form.Item name={['model', 'teacherContents']} label="讲师名称">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name={['model', 'resourcer']} label="资源所有者">
                    <Select allowClear>{options}</Select>
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item name={['model', 'videoUrl']} label="视频地址">
                <Input />
              </Form.Item>

              <Row gutter={4}>
                <Col span={6}>
                  <Form.Item name={['model', 'minAge']} label="适龄最小天数">
                    <Input type="number" min={0} />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name={['model', 'maxAge']} label="适龄最大天数">
                    <Input type="number" min={0} />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name={['model', 'apprvStaus']} label="审核状态">
                    <Input defaultValue="未审核" readOnly />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name={['model', 'watchCount']} label="浏览次数">
                    <Input type="number" min="0" readOnly />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={4}>
                <Col span={8}>
                  <Form.Item name={['model', 'beans']} label="观看币">
                    <InputNumber min={0} step={5} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name={['model', 'orderId']}
                    label="排序号"
                    tooltip="请按升序填写排序号"
                  >
                    <InputNumber style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name={['model', 'recommendNum']}
                    label="推荐号"
                    tooltip="请按升序填写推荐号"
                  >
                    <InputNumber style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'isFree']} valuePropName="checked">
                    <Checkbox>免费</Checkbox>
                  </Form.Item>
                  <Form.Item name={['model', 'isRec']} valuePropName="checked">
                    <Checkbox>推荐</Checkbox>
                  </Form.Item>
                  <Form.Item name={['model', 'isTop']} valuePropName="checked">
                    <Checkbox>置顶</Checkbox>
                  </Form.Item>
                  <Form.Item name={['model', 'isApprv']} valuePropName="checked">
                    <Checkbox disabled>审核</Checkbox>
                  </Form.Item>
                  <Form.Item name={['model', 'apprver']}>
                    <Input placeholder="请输入审核人" />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
            </TabPane>
            <TabPane tab="内容" key="2">
              <Form.Item
                name={['model', 'contents']}
                rules={[{ required: true, message: '请输入课程内容' }]}
                label="课程内容"
              >
                <BraftEditor
                  onChange={this.handleChange}
                  style={{ width: '100%', border: '1px dotted #ccc' }}
                  media={{ uploadFn: this.myUploadFn }}
                  controls={editorTools}
                  colors={[
                    '#000000',
                    '#333333',
                    '#666666',
                    '#999999',
                    '#cccccc',
                    '#ffffff',
                    '#61a951',
                    '#16a085',
                    '#07a9fe',
                    '#003ba5',
                    '#8e44ad',
                    '#f32784',
                    '#c0392b',
                    '#d35400',
                    '#f39c12',
                    '#fdda00',
                    '#7f8c8d',
                    '#2c3e50',
                    '#a800ff',
                    '#f234e7',
                    '#fd8bf6',
                  ]}
                />
              </Form.Item>
            </TabPane>
            <TabPane tab="图片" key="3">
              <Form.Item>
                <Upload
                  style={{ display: 'block' }}
                  action={UploadUtil.actionURL}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: 'Edu_Course',
                    objectField: 'imageUrl',
                  }}
                  name="files"
                  listType="picture-card"
                  fileList={fileList}
                  onChange={this.handleUpload}
                  multiple={true}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              </Form.Item>
              <Form.Item>
                <Button onClick={() => this.setState({ visible4: true })}>选择图片</Button>
              </Form.Item>
            </TabPane>
            <TabPane tab="优惠券" key="4">
              <Form.Item name={['model', 'coupons']}>
                <Transfer
                  dataSource={couponDatas}
                  titles={['所有优惠券', '已选优惠券']}
                  targetKeys={targetKeys}
                  selectedKeys={selectedKeys}
                  onChange={this.handleTransChange}
                  onSelectChange={this.handleSelectChange}
                  render={(item: any) => item.title}
                  style={{ marginBottom: 16 }}
                />
              </Form.Item>
            </TabPane>
            <TabPane tab="限时活动" key="5">
              <Form.Item name={['model', 'promotionId']}>
                <Transfer
                  dataSource={promotions}
                  titles={['所有活动', '已选活动']}
                  targetKeys={targetProKeys}
                  selectedKeys={selectedProKeys}
                  onChange={this.handleProTransChange}
                  onSelectChange={this.handleProSelectChange}
                  render={(item: any) => item.title}
                  style={{ marginBottom: 16 }}
                />
              </Form.Item>
            </TabPane>
            <TabPane tab="推荐拓展" key="6">
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => this.setState({ visibleExpand: true })}
                style={{ marginBottom: 12 }}
              >
                添加推荐拓展
              </Button>
              <Table
                rowKey="id"
                loading={loading}
                components={components}
                rowClassName={() => 'editable-row'}
                columns={columns as ColumnTypes}
                dataSource={expandList}
                scroll={{ y: 300 }}
              />
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={this.state.loading}>
                {text}
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button onClick={this.CopyData} disabled={!datas.id}>
                复制
              </Button>
              <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Modal
          title="图片选择"
          visible={this.state.visible4}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible4: false })}
          width={750}
          footer={false}
        >
          <ImgQuick clickFun={(val: any) => this.clickFun(val)} />
        </Modal>
        <Modal
          title="选择课程"
          visible={visibleExpand}
          destroyOnClose={true}
          onCancel={() => this.setState({ visibleExpand: false })}
          width={900}
          footer={false}
        >
          <ChoiceCourse
            id={courseId}
            editStatus={'expand'}
            onSelectChange={(val: any, valData: any) => this.handleSelect(val, valData)}
            getExpandList={this.getExpandList}
          />
        </Modal>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(CourseEdit);
